package yunjiao.javatutorials.guava.concurrent.spring;

import com.google.common.util.concurrent.AbstractIdleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 配置重载服务， SmartLifecycle 接口
 *
 * @author yangyunjiao
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConfigReloadService  extends AbstractIdleService implements SmartLifecycle {

    private final Map<String, String> configCache = new ConcurrentHashMap<>();
    private ScheduledExecutorService scheduler;

    private final ServiceProperties serviceProperties;


    @Override
    protected void startUp() throws Exception {
        log.info("Starting configuration reload service");

        // 加载初始配置
        loadConfigurationFromSources();

        // 创建定时任务
        scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = new Thread(r, "config-reloader");
            t.setDaemon(true);
            return t;
        });

        long refreshInterval = serviceProperties.getConfigRefreshInterval();
        // 定期重新加载配置
        scheduler.scheduleAtFixedRate(
                this::reloadConfiguration,
                refreshInterval, refreshInterval, TimeUnit.SECONDS
        );

        log.info("Configuration service started with refresh interval: " + refreshInterval + "s");
    }

    @Override
    protected void shutDown() throws Exception {
        log.info("Stopping configuration reload service");

        if (scheduler != null) {
            scheduler.shutdown();
            try {
                if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                    scheduler.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduler.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }

        configCache.clear();
    }

    private void loadConfigurationFromSources() {
        // 这里可以从数据库、配置文件、配置中心等加载配置
        configCache.put("feature.flag.new.ui", "true");
        configCache.put("api.rate.limit", "1000");
        configCache.put("cache.ttl.seconds", "300");
        configCache.put("log.level", "INFO");

        log.info("Loaded " + configCache.size() + " configuration entries");
    }

    private void reloadConfiguration() {
        try {
            log.debug("Reloading configuration...");
            // 模拟配置重新加载
            loadConfigurationFromSources();
        } catch (Exception e) {
            log.error("Failed to reload configuration: " + e.getMessage());
        }
    }

    public String getConfig(String key) {
        return configCache.get(key);
    }

    public String getConfig(String key, String defaultValue) {
        return configCache.getOrDefault(key, defaultValue);
    }

    public void updateConfig(String key, String value) {
        configCache.put(key, value);
    }

    @Override
    public void start() {
        if (!this.isRunning()) {
            this.startAsync().awaitRunning();
        }
    }

    @Override
    public void stop() {
        if (this.isRunning()) {
            this.stopAsync().awaitTerminated();
        }
    }

    @Override
    public boolean isAutoStartup() {
        return SmartLifecycle.super.isAutoStartup();
    }
}
